package top.eggcode.modules.user.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.eggcode.common.lang.BeanUnit;
import top.eggcode.component.query.model.PageList;
import top.eggcode.modules.user.model.*;
import top.eggcode.modules.user.store.PowerStore;
import top.eggcode.modules.user.store.RolePowerRepository;
import top.eggcode.modules.user.store.RoleRepository;
import top.eggcode.modules.user.store.RoleStore;
import top.eggcode.base.BaseMarkServiceImpl;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * Title: 角色服务实现
 * Description: TODO
 * Date: 2021/4/13 23:25
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Service
public class RoleService extends BaseMarkServiceImpl<RoleEntity> {

    private final RoleRepository selfRepository;

    private final RoleStore roleStore;

    private final PowerStore powerStore;

    private final RolePowerRepository rolePowerRepository;


    @Override
    public Optional<RoleEntity> get(String id) {
        return selfRepository.findById(id);
    }


    public Optional<RoleEntity> findByName(String name) {
        List<RoleEntity> roleList = selfRepository.findByName(name);

        if (roleList.size() == 1) {
            return Optional.of(roleList.get(0));
        }
        return Optional.empty();
    }


    public List<RoleEntity> findListById(List<String> idList) {
        return selfRepository.findAllById(idList);
    }


    public PageList<RoleEntity> page(RoleQuery query) {
        return roleStore.list(query);
    }


    public Optional<RoleBiz> getFull(String id) {
        RoleBiz biz = new RoleBiz();
        roleStore.findById(id).ifPresent(entity -> {
            BeanUnit.copy(entity, biz);
        });

        List<rolePowerEntity> relationList = rolePowerRepository.findByRoleId(id);
        List<PowerEntity> powerList = new LinkedList<>();
        relationList.forEach(relation -> powerStore.findById(relation.getPowerId()).ifPresent(powerList::add));

        biz.setPowerList(powerList);
        return Optional.of(biz);
    }
}
